package com.wangmeng.book.client.frame;

import com.wangmeng.book.client.service.CommandService;
import com.wangmeng.book.utils.ConstValueUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
import java.util.List;

/**
 * User: 王猛
 * Date: 13-10-9
 */
public class BookPublishManage {
    public static final int PAGE_SIZE = 50;
    private JPanel root;
    private JPanel controlPanel;
    private JButton allButton;
    private JButton publishButton;
    private JButton rejectButton;
    private JTable dataTable;
    private JScrollPane dataPanel;
    private JPanel pagePanel;
    private JButton forwordPageBnt;
    private JButton nextPageBnt;
    private int currentPage = 1;
    private static Vector headerNames = new Vector();
    private Vector data = new Vector();
    private MyCheckAllRenderer allCheck = new MyCheckAllRenderer();
    private List<Integer> statusList = new ArrayList<Integer>();
    private Map<String, Object> exParam = new HashMap<String, Object>();
    private static Map<Integer, String> statusMap = new HashMap<Integer, String>();

    static {
        headerNames.add("");
        headerNames.add("ID");
        headerNames.add("标题");
        headerNames.add("作者");
        headerNames.add("所属分类");
        headerNames.add("字数");
        headerNames.add("状态");
        headerNames.add("原始链接");
        statusMap.put(ConstValueUtils.APPROVE_RECEIVE_SUCCESS, "接收成功");
        statusMap.put(ConstValueUtils.APPROVE_HAS_UPDATE, "有更新");
    }

    public BookPublishManage() {
        statusList.add(ConstValueUtils.APPROVE_RECEIVE_SUCCESS);
        statusList.add(ConstValueUtils.APPROVE_HAS_UPDATE);
        JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
        if (dataList != null) {
            if (dataList.size() < PAGE_SIZE) {
                nextPageBnt.setEnabled(false);
            }
            for (int i = 0; i < dataList.size(); i++) {
                JSONObject obj = dataList.getJSONObject(i);
                Vector item = new Vector();
                item.add(false);
                item.add(obj.getInt("oid"));
                item.add(obj.getString("name"));
                item.add(obj.getString("author"));
                item.add(obj.getString("part_name"));
                item.add(obj.getInt("word_num"));
                String sn = statusMap.get(obj.getInt("approve_status"));
                item.add(sn == null ? "未知" : sn);
                String href = obj.getString("href");
                item.add(href);
                data.add(item);
            }
        } else {
            nextPageBnt.setEnabled(false);
        }

        DefaultTableModel tm = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                //禁用可编辑
                if (column > 0) {
                    return false;
                }
                return super.isCellEditable(row, column);
            }
        };
        tm.setDataVector(data, headerNames);
        dataTable.setModel(tm);
        TableColumn tc = dataTable.getColumnModel().getColumn(1);
        tc.setPreferredWidth(0);
        tc.setMaxWidth(0);
        tc.setMinWidth(0);
        tc.sizeWidthToFit();
        dataTable.getTableHeader().getColumnModel().getColumn(1).setMaxWidth(0);
        dataTable.getTableHeader().getColumnModel().getColumn(1).setMinWidth(0);
        tc = dataTable.getColumnModel().getColumn(0);
        tc.setPreferredWidth(30);
        tc.setMaxWidth(30);
        tc.setMinWidth(30);
        tc.sizeWidthToFit();
        tc.setHeaderRenderer(allCheck);
        tc.setCellEditor(dataTable.getDefaultEditor(Boolean.class));
        tc.setCellRenderer(dataTable.getDefaultRenderer(Boolean.class));
        tc.getCellEditor().addCellEditorListener(new CellEditorListener() {
            public void editingStopped(ChangeEvent e) {
                int rowNum = dataTable.getRowCount();
                int notNum = 0;
                for (int i = 0; i < rowNum; i++) {
                    Object value = dataTable.getValueAt(i, 0);
                    if (!((Boolean) value)) {
                        notNum++;
                    }
                }
                if (notNum == 0) {
                    allCheck.setSelected(true);
                    dataTable.getTableHeader().repaint();
                } else if (notNum == 1) {
                    allCheck.setSelected(false);
                    dataTable.getTableHeader().repaint();
                }
            }

            public void editingCanceled(ChangeEvent e) {

            }
        });
        dataTable.getTableHeader().addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (dataTable.getColumnModel().getColumnIndexAtX(e.getX()) == 0) {
                    if (allCheck.isSelected()) {
                        allCheck.setSelected(false);
                        dataTable.getTableHeader().repaint();
                        for (int i = 0; i < dataTable.getRowCount(); i++) {
                            dataTable.getModel().setValueAt(false, i, 0);//把这一列都设成和表头一样
                        }
                    } else {
                        allCheck.setSelected(true);
                        dataTable.getTableHeader().repaint();
                        for (int i = 0; i < dataTable.getRowCount(); i++) {
                            dataTable.getModel().setValueAt(true, i, 0);//把这一列都设成和表头一样
                        }
                    }
                }
            }
        });
        dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        nextPageBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                data.clear();
                JSONArray dataList = CommandService.getInstance().listBook(++currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
                if (dataList != null) {
                    if (dataList.size() < PAGE_SIZE) {
                        nextPageBnt.setEnabled(false);
                    }
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject obj = dataList.getJSONObject(i);
                        Vector item = new Vector();
                        item.add(false);
                        item.add(obj.getInt("oid"));
                        item.add(obj.getString("name"));
                        item.add(obj.getString("author"));
                        item.add(obj.getString("part_name"));
                        item.add(obj.getInt("word_num"));
                        String sn = statusMap.get(obj.getInt("approve_status"));
                        item.add(sn == null ? "未知" : sn);
                        String href = obj.getString("href");
                        item.add(href);
                        data.add(item);
                    }
                } else {
                    nextPageBnt.setEnabled(false);
                }
                dataTable.updateUI();
                forwordPageBnt.setEnabled(true);
            }
        });
        forwordPageBnt.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                data.clear();
                JSONArray dataList = CommandService.getInstance().listBook(--currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
                if (dataList != null) {
                    for (int i = 0; i < dataList.size(); i++) {
                        JSONObject obj = dataList.getJSONObject(i);
                        Vector item = new Vector();
                        item.add(false);
                        item.add(obj.getInt("oid"));
                        item.add(obj.getString("name"));
                        item.add(obj.getString("author"));
                        item.add(obj.getString("part_name"));
                        item.add(obj.getInt("word_num"));
                        String sn = statusMap.get(obj.getInt("approve_status"));
                        item.add(sn == null ? "未知" : sn);
                        String href = obj.getString("href");
                        item.add(href);
                        data.add(item);
                    }
                }
                dataTable.updateUI();
                nextPageBnt.setEnabled(true);
                if (currentPage == 1) {
                    forwordPageBnt.setEnabled(false);
                }
            }
        });
        dataTable.setCellSelectionEnabled(true);
        dataTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (e.getClickCount() == 2) {
                    if (dataTable.getColumnModel().getColumnIndexAtX(e.getX()) == 7) {
                        String url = (String) dataTable.getValueAt(dataTable.getSelectedRow(), dataTable.getSelectedColumn());
                        try {
                            Desktop.getDesktop().browse(new URI(url));
                        } catch (IOException e1) {
                            e1.printStackTrace();
                        } catch (URISyntaxException e1) {
                            e1.printStackTrace();
                        }
                    }
                }
            }
        });

        allButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                Object rb = CommandService.getInstance().publishBook(1, null);
                if (rb != null && (Integer) rb > 0) {
                    currentPage = 0;
                    data.clear();
                    JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
                    if (dataList != null) {
                        for (int i = 0; i < dataList.size(); i++) {
                            JSONObject obj = dataList.getJSONObject(i);
                            Vector item = new Vector();
                            item.add(false);
                            item.add(obj.getInt("oid"));
                            item.add(obj.getString("name"));
                            item.add(obj.getString("author"));
                            item.add(obj.getString("part_name"));
                            item.add(obj.getInt("word_num"));
                            String sn = statusMap.get(obj.getInt("approve_status"));
                            item.add(sn == null ? "未知" : sn);
                            String href = obj.getString("href");
                            item.add(href);
                            data.add(item);
                        }
                    }
                    dataTable.updateUI();
                    forwordPageBnt.setEnabled(false);
                }
            }
        });

        publishButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int rowCount = dataTable.getRowCount();
                List<Integer> idList = new ArrayList<Integer>();
                for (int i = 0; i < rowCount; i++) {
                    Boolean checked = (Boolean) dataTable.getValueAt(i, 0);
                    if (checked) {
                        Integer oid = (Integer) dataTable.getValueAt(i, 1);
                        idList.add(oid);
                    }
                }
                if (idList.size() == 0) {
                    JOptionPane.showMessageDialog(root, "请先选择要操作的记录?", "警告信息", JOptionPane.WARNING_MESSAGE | JOptionPane.OK_OPTION);
                } else {
                    Object rb = CommandService.getInstance().publishBook(2, idList);
                    if (rb != null && (Integer) rb > 0) {
                        if ((Integer) rb == rowCount && rowCount < PAGE_SIZE) {
                            currentPage = currentPage - 1 > 0 ? (currentPage - 1) : 1;
                        }
                        data.clear();
                        JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
                        if (dataList != null) {
                            for (int i = 0; i < dataList.size(); i++) {
                                JSONObject obj = dataList.getJSONObject(i);
                                Vector item = new Vector();
                                item.add(false);
                                item.add(obj.getInt("oid"));
                                item.add(obj.getString("name"));
                                item.add(obj.getString("author"));
                                item.add(obj.getString("part_name"));
                                item.add(obj.getInt("word_num"));
                                String sn = statusMap.get(obj.getInt("approve_status"));
                                item.add(sn == null ? "未知" : sn);
                                String href = obj.getString("href");
                                item.add(href);
                                data.add(item);
                            }
                        }
                        dataTable.updateUI();
                        if (currentPage == 1) {
                            forwordPageBnt.setEnabled(false);
                        }
                    }
                }
            }
        });

        rejectButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int rowCount = dataTable.getRowCount();
                List<Integer> idList = new ArrayList<Integer>();
                for (int i = 0; i < rowCount; i++) {
                    Boolean checked = (Boolean) dataTable.getValueAt(i, 0);
                    if (checked) {
                        Integer oid = (Integer) dataTable.getValueAt(i, 1);
                        idList.add(oid);
                    }
                }
                if (idList.size() == 0) {
                    JOptionPane.showMessageDialog(root, "请先选择要操作的记录?", "警告信息", JOptionPane.WARNING_MESSAGE | JOptionPane.OK_OPTION);
                } else {
                    Object rb = CommandService.getInstance().publishBook(3, idList);
                    if (rb != null && (Integer) rb > 0) {
                        if ((Integer) rb == rowCount && rowCount < PAGE_SIZE) {
                            currentPage = currentPage - 1 > 0 ? (currentPage - 1) : 1;
                        }
                        data.clear();
                        JSONArray dataList = CommandService.getInstance().listBook(currentPage, PAGE_SIZE, statusList, "oid asc", exParam);
                        if (dataList != null) {
                            for (int i = 0; i < dataList.size(); i++) {
                                JSONObject obj = dataList.getJSONObject(i);
                                Vector item = new Vector();
                                item.add(false);
                                item.add(obj.getInt("oid"));
                                item.add(obj.getString("name"));
                                item.add(obj.getString("author"));
                                item.add(obj.getString("part_name"));
                                item.add(obj.getInt("word_num"));
                                String sn = statusMap.get(obj.getInt("approve_status"));
                                item.add(sn == null ? "未知" : sn);
                                String href = obj.getString("href");
                                item.add(href);
                                data.add(item);
                            }
                        }
                        dataTable.updateUI();
                        if (currentPage == 1) {
                            forwordPageBnt.setEnabled(false);
                        }
                    }
                }
            }
        });
    }

    public JPanel getRoot() {
        return root;
    }
}
